/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormPessoa.java
 *
 * Created on 17/03/2011, 19:39:26
 */

package Interface;

import Interface.Combos.Itens;
import Modelo.ConexaoBD;
import classes.Parameters;
import classes.Relatorio;
import classes.Validacao;
import java.io.FileInputStream;
import java.sql.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Form para cadastro de formulários
 * @author Jonas Gualberto Diel [jonasdiel@gmail.com]
 */
public class FormRelatorios extends javax.swing.JInternalFrame {

    public static Connection con;
    public static Statement stmt;
    private static String FUNCTION;

    private int questionCategoryId; //Chave primária da tabela
    
    /** Creates new form FormPessoa */
    public FormRelatorios() {
        abreConexao();
        initComponents();
        preparaCBRelatorio();
//        preparaCBFormato();
        preparaComboBoxFormulario();
    }

    //Abre uma conexão com o banco de dados
    private void abreConexao() {
        try {
            con = ConexaoBD.getInstance().getConnection();
            stmt = con.createStatement();
        } catch (Exception e) {
            System.out.print(e);
        }
    }

//    public void preparaCBFormato()
//    {
//        formato.removeAllItems();
//        formato.addItem("PDF");
//        formato.addItem("DOC");
//        formato.addItem("ODT");        
//    }
    
    
    
    public void preparaCBRelatorio()
    {
        relatorio.removeAllItems();
        relatorio.addItem("");
        relatorio.addItem("Formlário");
//        relatorio.addItem("Gabario");
//        relatorio.addItem("Grade de respostas");
//        relatorio.addItem("Resultados");
    }
    
    public void preparaComboBoxFormulario()
    {
        // Populando as combos
        Combos cmb = new Combos("rshForm");
        Map<String, Itens> m = cmb.getMap();
        formId.removeAllItems(); // limpa Combo        
        formId.addItem("::Selecione::"); // Preenche a primeira opcao
        Set<String> chaves = m.keySet();
        Iterator<String> it = chaves.iterator();
        while (it.hasNext()) {
        String chave = it.next();
        formId.addItem(chave);
        
        }
    }  

    /**
     * @param aFUNCTION the FUNCTION to set
     */
    public static void setFunction(String aFUNCTION) {
        FUNCTION = aFUNCTION;
    }

     /**
     * @return the FUNCTION
     */
    public static String getFunction() {
        return FUNCTION;
    }

    /**
     * Método para validar os campos do formulário
     * @return
     */
    private boolean validarCampos()
    {
        validaRelatorio.setText("");
        validaFormId.setText("");
        
        boolean retorno = true;
        
        if( !(String.valueOf(relatorio.getSelectedItem()).length() > 0) ) //Relatorio
        {
            validaRelatorio.setText(Validacao.ERRO_CAMPO_OBRIGATORIO);
            return false;
        }
        
        if( relatorio.getSelectedItem() == "Formlário")
        {
            if( formId.getSelectedIndex() == 0 ) //Formulario
            {
                validaFormId.setText(Validacao.ERRO_CAMPO_OBRIGATORIO);
                 retorno = false;
            }
        }
        if( relatorio.getSelectedItem() == "Gabario")
        {
            
        }
        if( relatorio.getSelectedItem() == "Grade de respostas")
        {
            
        }
        if( relatorio.getSelectedItem() == "Resultados")
        {
            
        }  
        
        /**
         * 
                validaFormId.setText("");
                if( formId.getSelectedIndex() == 0 )
                {
                    validaFormId.setText(Validacao.ERRO_CAMPO_OBRIGATORIO);
                }
         */

        return retorno;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnGerar = new javax.swing.JButton();
        validaRelatorio = new javax.swing.JLabel();
        labelRelatorio = new javax.swing.JLabel();
        relatorio = new javax.swing.JComboBox();
        painelQuestionario = new javax.swing.JPanel();
        validaFormId = new javax.swing.JLabel();
        formId = new javax.swing.JComboBox();
        labelFormId = new javax.swing.JLabel();
        painelGabarito = new javax.swing.JPanel();
        painelGrade = new javax.swing.JPanel();
        painelResultados = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createEtchedBorder());
        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        setIconifiable(true);
        setTitle("Gerar Relatório");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("FormRelatorio"); // NOI18N

        btnGerar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Interface/imagens/menu/report.png"))); // NOI18N
        btnGerar.setText("Gerar");
        btnGerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGerarActionPerformed(evt);
            }
        });

        validaRelatorio.setForeground(new java.awt.Color(255, 0, 0));

        labelRelatorio.setText("Relatório:");

        relatorio.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        relatorio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                relatorioActionPerformed(evt);
            }
        });

        validaFormId.setForeground(new java.awt.Color(255, 0, 0));

        formId.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        formId.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                formIdActionPerformed(evt);
            }
        });
        formId.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formIdKeyPressed(evt);
            }
        });

        labelFormId.setText("Formulário:");

        javax.swing.GroupLayout painelQuestionarioLayout = new javax.swing.GroupLayout(painelQuestionario);
        painelQuestionario.setLayout(painelQuestionarioLayout);
        painelQuestionarioLayout.setHorizontalGroup(
            painelQuestionarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelQuestionarioLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelFormId)
                .addGap(59, 59, 59)
                .addComponent(formId, 0, 277, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(validaFormId, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        painelQuestionarioLayout.setVerticalGroup(
            painelQuestionarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelQuestionarioLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(painelQuestionarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(validaFormId, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(painelQuestionarioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(labelFormId)
                        .addComponent(formId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(33, Short.MAX_VALUE))
        );

        painelGabarito.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout painelGabaritoLayout = new javax.swing.GroupLayout(painelGabarito);
        painelGabarito.setLayout(painelGabaritoLayout);
        painelGabaritoLayout.setHorizontalGroup(
            painelGabaritoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 620, Short.MAX_VALUE)
        );
        painelGabaritoLayout.setVerticalGroup(
            painelGabaritoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 64, Short.MAX_VALUE)
        );

        painelGrade.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout painelGradeLayout = new javax.swing.GroupLayout(painelGrade);
        painelGrade.setLayout(painelGradeLayout);
        painelGradeLayout.setHorizontalGroup(
            painelGradeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 620, Short.MAX_VALUE)
        );
        painelGradeLayout.setVerticalGroup(
            painelGradeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 64, Short.MAX_VALUE)
        );

        painelResultados.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout painelResultadosLayout = new javax.swing.GroupLayout(painelResultados);
        painelResultados.setLayout(painelResultadosLayout);
        painelResultadosLayout.setHorizontalGroup(
            painelResultadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 620, Short.MAX_VALUE)
        );
        painelResultadosLayout.setVerticalGroup(
            painelResultadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 64, Short.MAX_VALUE)
        );

        jLabel1.setText("Opções de geração:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(labelRelatorio)
                        .addGap(18, 18, 18)
                        .addComponent(relatorio, 0, 378, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(validaRelatorio, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(48, 48, 48))
                    .addComponent(btnGerar)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(painelQuestionario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(painelGabarito, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(painelGrade, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(painelResultados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addContainerGap(535, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(labelRelatorio)
                        .addComponent(relatorio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(validaRelatorio, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(painelQuestionario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(painelGrade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(painelGabarito, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(painelResultados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 120, Short.MAX_VALUE)
                .addComponent(btnGerar)
                .addGap(19, 19, 19))
        );

        getAccessibleContext().setAccessibleName("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGerarActionPerformed
        
        String fileQuestionario = "";
        
        //Validação dos campos
        if( this.validarCampos() )
        {
            try {
                //Carrega as informaçoes do relatorios
                Properties prop = new Properties();            
                prop.load(new FileInputStream("REPORTS.properties"));
                fileQuestionario = prop.getProperty("report.questionario.path");
            } 
            catch (Exception e) 
            {
                System.err.println(e);
            }
            
            if( relatorio.getSelectedItem() == "Formlário")
            {
               
                //Obtem valor da combo de formulario
                Combos cmbForm = new Combos("rshForm");
                Map<String, Itens> mForm = cmbForm.getMap();
                Itens dataForm = mForm.get(formId.getSelectedItem());
                
                //Cria os parametros para geracao            
                Parameters[] parametros = new Parameters[1];
                parametros[0] = new Parameters();
                parametros[0].var = "formId";
                parametros[0].value = dataForm.getCodigo();            
                //gera o relatorio
                Relatorio rel = new Relatorio(fileQuestionario, con, parametros);                
                rel.gerar();
            }
        }
    }//GEN-LAST:event_btnGerarActionPerformed

    
    private void relatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_relatorioActionPerformed
        /**
         * Ao selecionar um relatorio atualizar o panel com os campos nevessarios para a geracao do respectivo
         * relatorio selecionado
         */
        String rel = String.valueOf(relatorio.getSelectedItem());
        
        this.setSize(646, 360);
        //[646, 466]
        
        painelQuestionario.setVisible(false);
        painelQuestionario.setSize(0, 0);
        
        painelGabarito.setVisible(false);
        painelGabarito.setSize(0, 0);
        
        painelGrade.setVisible(false);
        painelGrade.setSize(0, 0);
        
        painelResultados.setVisible(false);
        painelResultados.setSize(0, 0);
        
        if( rel.length() >0 )
        {
            if( rel == "Formlário")
            {
                painelQuestionario.setVisible(true);
                painelQuestionario.setSize(622, 66);
                
            }
            if( rel == "Gabario")
            {
                painelGabarito.setVisible(true);
                painelGabarito.setSize(622, 66);
            }
            if( rel == "Grade de respostas")
            {
                painelGrade.setVisible(true);
                painelGrade.setSize(622, 66);
            }
            if( rel == "Resultados")
            {
                painelResultados.setVisible(true);
                painelResultados.setSize(622, 66);
            }  
        }
    }//GEN-LAST:event_relatorioActionPerformed

    private void formIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_formIdActionPerformed
        
}//GEN-LAST:event_formIdActionPerformed

    private void formIdKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formIdKeyPressed
        
}//GEN-LAST:event_formIdKeyPressed


    @Override
    public void setDefaultCloseOperation(int operation) {

        
        super.setDefaultCloseOperation(operation);
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGerar;
    private javax.swing.JComboBox formId;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel labelFormId;
    private javax.swing.JLabel labelRelatorio;
    private javax.swing.JPanel painelGabarito;
    private javax.swing.JPanel painelGrade;
    private javax.swing.JPanel painelQuestionario;
    private javax.swing.JPanel painelResultados;
    private javax.swing.JComboBox relatorio;
    private javax.swing.JLabel validaFormId;
    private javax.swing.JLabel validaRelatorio;
    // End of variables declaration//GEN-END:variables

}
